package com.hightemperator.Interceptors;

import com.hightemperator.util.LocalResponseBody;
import com.hightemperator.util.SendMsgUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

public class APIInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {

        String token = request.getParameter("token");

        // token is not needed when debug
        if (token == null) {
            response.setStatus(401);
            SendMsgUtil.sendJsonMessage(response, new LocalResponseBody<>("用户校验失败").noAuth());
            return false;
        }  // !! remember to comment this when deploy on server !!

        String userStr= (String) request.getServletContext().getAttribute(token);

        if (userStr==null||userStr.equals("")) {
            response.setStatus(401);
            SendMsgUtil.sendJsonMessage(response, new LocalResponseBody<>("用户校验失败").noAuth());
            return false;
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {

    }


    public void dealErrorReturn(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object obj) {


    }

}
